package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @GetMapping("/userInfo")
    public String userInfo(HttpServletRequest request) {
        // 自动从redis中拿session
        String loginUser = (String) request.getSession().getAttribute("loginUser");
        // 访问首页，先判断是否登录，没登录转发到登录页
        if(loginUser == null || loginUser.length() == 0){
            return "login";
        } else {
            return "userInfo";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUser");
        return "login";
    }

    @GetMapping({"/index", "/"})
    public String index(HttpServletRequest request) {
        String loginUser = (String) request.getSession().getAttribute("loginUser");
        // 访问首页，先判断是否登录，没登录转发到登录页
        if(loginUser == null || loginUser.length() == 0){
            return "login";
        } else {
            return "index";
        }
    }

    @PostMapping("/login")
    public String login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //校验用户名密码
        if (username != null && username.equals(password)) {
            // 自动把loginUser放到redis
            request.getSession().setAttribute("loginUser", username);
            return "index";
        } else {
            return "redirect:toLogin";
        }
    }
}
